package com.xsm.activitygroup;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

import com.xsm.DataBase.ReadMessage;
import com.xsm.DataBase.SaveMessage;
import com.xsm.adapter.gradviewAdapter;
import com.xsm.internet.PostMessage;
import com.xsm.view.MyGridView;
import com.xsm.view.Mydialog;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class activity1  extends Activity{
	private LinearLayout parentView;
	private LinearLayout MainView;
	private Activity context;
	private  ImageView[] imageViews = null;
	private ImageView imageView = null;
	private ViewPager advPager = null;
	private AtomicInteger what = new AtomicInteger(0);
	private boolean isContinue = true;
	private ArrayList<MyGridView> gridViews;
	private ArrayList<gradviewAdapter> adapters;
	private HomepageHandler handler;
	private TreeMap<String,ArrayList<String>> tHashtable;
	private RelativeLayout errorLayout;
	private RelativeLayout loadLayout;
	private String result="";
	private SharedPreferences sharedPreferences;
	private PackageInfo packInfo = null;
	private String newsString = "";
	private  TextView newsTextView;
	private  String oldString = "";
	  
	protected void onCreate(Bundle savedInstanceState) {
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	super.onCreate(savedInstanceState);
	setContentView(R.layout.homepage);
	context=this;
    initViewPager();
    handler=new HomepageHandler();
    sharedPreferences=getSharedPreferences("XSM", 0);
    
	parentView=(LinearLayout)findViewById(R.id.parentView);
	errorLayout=(RelativeLayout)findViewById(R.id.errorlayout);
	loadLayout=(RelativeLayout)findViewById(R.id.loadlayout);
	MainView=(LinearLayout)findViewById(R.id.MainView);
	
	adapters=new ArrayList<gradviewAdapter>();
	gridViews=new ArrayList<MyGridView>();
	loadLayout.setVisibility(View.VISIBLE);
	new GetRecommend().start();
     new getNews().execute();
	
	
	new Thread(new Runnable() {
		public void run() {
			Message msg=handler.obtainMessage();
			String packageName="";
			int versionCode=0;
			String versionName="";
	  PackageManager packageManager = getPackageManager();
	try {
		packInfo = packageManager.getPackageInfo(getPackageName(),0);
		packageName=packInfo.packageName;
		versionName= packInfo.versionName;
		versionCode=packInfo.versionCode;
		
	} catch (NameNotFoundException e) {
		e.printStackTrace();
	}
	sharedPreferences.edit().putString("packageName",packageName ).commit();
	sharedPreferences.edit().putString("versionname",versionName).commit();
	sharedPreferences.edit().putString("versioncode",versionCode+"").commit();
	
        List<NameValuePair> params=new ArrayList();
		params.add(new BasicNameValuePair("ASK","Update"));
		params.add(new BasicNameValuePair("packageName",packageName));
		params.add(new BasicNameValuePair("versioncode",versionCode+""));
PostMessage postMessage=new PostMessage(params);
result=postMessage.getResult();
JSONArray array = null;
try {
array=new JSONArray(result);
}catch (Exception e) {
}
if(result.equals("-1")==false&&array.length()>0){
	msg.what=2;
	handler.sendMessage(msg);
}

		}
	}).start();
	
	
}
	public void Search(View view){
		Intent intent=new Intent();
		intent.setClass(context,SearchView.class);
	    startActivity(intent);
	}
	
	public void Shownews(View paramView)
	  {
	    if (this.oldString.equals(""))
	      this.oldString = "暂时无最新公告";
	    Mydialog localMydialog = new Mydialog(this.context, this.oldString);
	    localMydialog.CancelText("知道了");
	    localMydialog.settitle("公告");
	    localMydialog.showDialog();
	  }
	
	protected void onResume() {
	for(int i=0;i<gridViews.size();i++){
		gridViews.get(i).setAdapter(adapters.get(i));
	}
		super.onResume();
	}
	
	
	private void initViewPager() {
		advPager = (ViewPager) findViewById(R.id.adv_pager);
		List<View> advPics = new ArrayList<View>();
		ImageView img1 = new ImageView(this);
		img1.setBackgroundResource(R.drawable.show1);
		advPics.add(img1);
		ImageView img2 = new ImageView(this);
		img2.setBackgroundResource(R.drawable.show2);
		advPics.add(img2);
		ImageView img3 = new ImageView(this);
		img3.setBackgroundResource(R.drawable.show4);
		advPics.add(img3);
		ImageView img4 = new ImageView(this);
		img4.setBackgroundResource(R.drawable.show3);
		advPics.add(img4);
		ViewGroup group = (ViewGroup) findViewById(R.id.viewGroup);
		imageViews = new ImageView[advPics.size()];
		for (int i = 0; i < advPics.size(); i++) {
			imageView = new ImageView(this);
			imageView.setLayoutParams(new LayoutParams(20, 20));
			imageView.setPadding(20, 0, 20, 0);
			imageViews[i] = imageView;
			if (i == 0) {			
				imageViews[i].setBackgroundResource(R.drawable.banner_dian_focus);
			} else {
				imageViews[i].setBackgroundResource(R.drawable.banner_dian_blur);
			}
			group.addView(imageViews[i]);
		}
		advPager.setAdapter(new AdvAdapter(advPics));
		advPager.setOnPageChangeListener(new GuidePageChangeListener());	
		advPager.setOnTouchListener(new View.OnTouchListener() {	
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_MOVE:
					isContinue = false;
					break;
				case MotionEvent.ACTION_UP:
					isContinue = true;
					break;
				default:
					isContinue = true;
					break;
				}
				return false;
			}});
		new Thread(new Runnable() {
			public void run() {
				while (true) {
					if (isContinue) {
						viewHandler.sendEmptyMessage(what.get());
						whatOption();
					}
				}
			}
		}).start();
	}
	private void whatOption() {
		what.incrementAndGet();
		if (what.get() > imageViews.length - 1) {
			what.getAndAdd(-4);
		}
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			
		}
	}
	private final Handler viewHandler = new Handler() {
		public void handleMessage(Message msg) {
			advPager.setCurrentItem(msg.what);
			super.handleMessage(msg);
		}

	};
	private final class GuidePageChangeListener implements OnPageChangeListener {
		public void onPageScrollStateChanged(int arg0) {

		}
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		public void onPageSelected(int arg0) {
			for (int i = 0; i < imageViews.length; i++) {
				imageViews[arg0]
						.setBackgroundResource(R.drawable.banner_dian_focus);
				if (arg0 != i) {
					imageViews[i]
							.setBackgroundResource(R.drawable.banner_dian_blur);
				}
			}

		}

	}

	private final class AdvAdapter extends PagerAdapter {
		private List<View> views = null;
		public AdvAdapter(List<View> views) {
			this.views = views;
		}
		
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(views.get(arg1));
		}
		public void finishUpdate(View arg0) {
		}
		public int getCount() {
			return views.size();
		}
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(views.get(arg1), 0);
			return views.get(arg1);
		}
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}
		public Parcelable saveState() {
			return null;
		}
		public void startUpdate(View arg0) {
		}
	}

	
class GetRecommend extends Thread{
	public void run() {
	String o=sharedPreferences.getString("orecommendv", "");
	String n=sharedPreferences.getString("nrecommendv","0");	
	String  re="";
	   if(!o.equals(n))
	re=new SaveMessage(context).initRecommend();
	 if(re.equals("1")){
	sharedPreferences.edit().putString("orecommendv",n).commit();	
	 }
	 tHashtable=new ReadMessage(context).getrecommend();
		Message msg=handler.obtainMessage();
		if(tHashtable.size()>0){
		msg.what=1;
		}else {
		msg.what=-2;	
		}	
		handler.sendMessage(msg);
	}
}
	

private void  initGridView(TreeMap<String,ArrayList<String>> hashtable){
	Iterator<String> iterator_2 = hashtable.keySet().iterator(); 
	while (iterator_2.hasNext()) { 
	Object key = iterator_2.next(); 
	final ArrayList<String> content=hashtable.get(key);
	View view=LayoutInflater.from(context).inflate(R.layout.gridchildview, null);
	MyGridView gridView1=(MyGridView)view.findViewById(R.id.t1);
	TextView textView=(TextView)view.findViewById(R.id.text);
	textView.setText(key.toString().substring(1, key.toString().length()));
	gridViews.add(gridView1);
	 gradviewAdapter adapter=new gradviewAdapter(context,content);
	 adapters.add(adapter);
	 gridView1.setAdapter(adapter);
	 gridView1.setOnItemClickListener(new OnItemClickListener() {
	 public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
		Intent intent=new Intent();
		intent.putExtra("press",content.get(position));
		intent.setClass(context,Tuijian.class);
		startActivity(intent);
			}
		});
	parentView.addView(view);
	} 
}

//重新获取推荐内容
public void Update(View view){
loadLayout.setVisibility(View.VISIBLE);
errorLayout.setVisibility(View.GONE);
new GetRecommend().start();	
}


class getNews extends AsyncTask<Void, Void, String>
{
 
  protected String doInBackground(Void[] paramArrayOfVoid)
  {
    ArrayList localArrayList = new ArrayList();
    localArrayList.add(new BasicNameValuePair("ASK", "getNews"));
    PostMessage localPostMessage = new PostMessage(localArrayList);
    activity1.this.newsString = localPostMessage.getResult();
    activity1.this.oldString = new SaveMessage(activity1.this.context).getnews();
    if (activity1.this.newsString.equals(""))
      return "";
    if (activity1.this.newsString.equals("-1"))
      return "";
    if (activity1.this.newsString.equals(activity1.this.oldString))
      return "";
    new SaveMessage(activity1.this.context).saveNews(activity1.this.newsString);
    return activity1.this.newsString;
  }

  protected void onPostExecute(String paramString)
  {
    if (!paramString.equals(""))
    {
      Mydialog localMydialog = new Mydialog(activity1.this.context, paramString);
      localMydialog.CancelText("知道了");
      localMydialog.settitle("公告");
      localMydialog.showDialog();
      activity1.this.oldString = paramString;
    }
  }
}


  class	HomepageHandler extends Handler{
  public void handleMessage(Message msg) {
	    //初始化推荐
		if(msg.what==1){
		MainView.setVisibility(View.VISIBLE);	
		errorLayout.setVisibility(View.GONE);
		loadLayout.setVisibility(View.GONE);	
		initGridView(tHashtable);
		}
		//发现跟新
		else if(msg.what==2){
			Intent intent=new Intent();
			intent.setClass(context,UpdateActivity.class);
			intent.putExtra("updatetext", result);
			startActivity(intent);
		}
		//获取推荐内容失败
		else if(msg.what==-2){
		loadLayout.setVisibility(View.GONE);	
		errorLayout.setVisibility(View.VISIBLE);	
		MainView.setVisibility(View.GONE);
		}
		//网络异常
		else if(msg.what==-1){
			Toast.makeText(context, R.string.neterror, Toast.LENGTH_LONG).show();
		}
	}
}
	
}
